package com.wk.worksetter

import android.content.pm.PackageInfo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.isGone
import com.wk.worksetter.adapter.MainListAdapter
import com.wk.worksetter.databinding.ActivityWorkSetterMainBinding
import com.wk.worksetter.view.AppsBottomDialog
import com.wk.worksetter.viewmodels.MainViewModel

class MainActivity : AppCompatActivity() {

    private val mAdapter = MainListAdapter()
    private lateinit var binding: ActivityWorkSetterMainBinding
    private val vm by viewModels<MainViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWorkSetterMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initViews()
        initObserve()
    }

    private fun initObserve() {
        vm.packageInfos.observe(this){
            vm.loadNotRunningInfos()
            binding.floatingActionButton.isGone = it.isNullOrEmpty()
        }
        vm.notRunningInfos.observe(this){list->
            list.forEach {
                it.icon = vm.appIconWithPackage[it.packageName]
            }
            mAdapter.setNewInstance(list.toMutableList())
        }
    }

    private fun initViews() {
        binding.floatingActionButton.isGone = vm.packageInfos.value.isNullOrEmpty()
        binding.floatingActionButton.setOnClickListener {fab->
            val dialog = AppsBottomDialog(vm.packageInfos.value,vm.appIconWithPackage)
            dialog.setOnChosenCallback(object : AppsBottomDialog.OnChosenCallback {
                override fun onChosen(info: PackageInfo) {
//                    val oneTimeRequest = OneTimeWorkRequest.Builder(StartAppWorker::class.java)
//                        .setInputData(
//                            Data.Builder().putString("packageName", info.packageName).build()
//                        )
//                        .build()
//                    WorkManager.getInstance(this@MainActivity)
//                        .getWorkInfoByIdLiveData(oneTimeRequest.id)
//                        .observe(this@MainActivity) { inf ->
//                            if (inf.state.isFinished) {
//                                val error = inf.outputData.getString("error")
//                                SnackUtil.show(error)
//                            }
//                        }
//                    WorkManager.getInstance(this@MainActivity).enqueue(oneTimeRequest)
                    vm.addPackInfoToList(info)
                    dialog.dismissAllowingStateLoss()
                }
            })
            dialog.showNow(supportFragmentManager, "apps")
        }

        binding.recyclerView.adapter = mAdapter

    }
}